package com.joint.web.action.party;

import cn.jpush.api.report.UsersResult;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.bean.DictBean;
import com.fz.us.dict.entity.Dict;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.RoleService;
import com.joint.base.service.TaskRecordService;
import com.joint.base.service.UsersService;
import com.joint.core.entity.*;
import com.joint.core.entity.SelectionApply;
import com.joint.core.service.SelectionApplyService;
import com.joint.core.service.SelectionApplyService;
import com.joint.core.service.SelectionNoticeService;
import com.joint.core.service.SelectionSpeechService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by dqf on 2015/8/26.
 */
@ParentPackage("party")
public class AjaxSelectionapplyAction extends BaseFlowAction {
  
    @Resource
    private SelectionApplyService selectionApplyService;
    @Resource
    private SelectionNoticeService selectionNoticeService;
    @Resource
    private SelectionSpeechService selectionSpeechService;
    @Resource
    private DictService dictService;
    @Resource
    private UsersService usersService;
    @Resource
    private RoleService roleService;
    @Resource
    private TaskRecordService taskRecordService;

    private SelectionApply selectionApply;
    private SelectionSpeech selectionSpeech;




    private int numStatus;
    private Users loginUser;

    //前台传到后台的数据
    private String attchmentId;
    private String checkUsersId;




    //从后台传回前台的数据
    private String attchmentFileId;

    //申请人信息
    private String applyUserName1;
    private String applyUserId;
    private String applyUserDate;

    private boolean flag;



    /**
     * 相关资料文本
     */
    private String attchmentText;
    /**
     * 相关资料
     */
    private List<FileManage> attchmentList;
    /**
     * 一个公告对应一个报名
     */
    private SelectionNotice selectionNotice;
    /**
     * 备注
     */
    private String remark;

    private String viewtype;
    private String todo;


    /**
     * 项目视图
     * @return
     */
    public String execute(){
        selectionNotice=new SelectionNotice();
        flag=false;
        pager=new Pager();
        Company company=usersService.getCompanyByUser();
        Users users=usersService.getLoginInfo();
        Map<String, Object> params=new HashMap<String, Object>();
        params=getSearchFilterParams(_search,params,filters);
        params.put("company",company);
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("creater",users);//一个用户只能申请一次
        if(StringUtils.isNotEmpty(parentId)){
            selectionNotice=selectionNoticeService.get(parentId);
            params.put("selectionNotice",selectionNotice);
        }


        pager=selectionApplyService.findByPager(pager,params);
        List<SelectionApply> selectionApplyList;
        if(pager.getTotalCount()>0){
            selectionApplyList=(List<SelectionApply>)pager.getList();
        }else {
            selectionApplyList=new ArrayList<>();
        }
       if(selectionApplyList.size()>0){
            flag=true;
       }

        return "selectionapply";
    }


    public String listfordialog(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();
        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        pager=selectionApplyService.findByPagerAndProcessState(pager, user, "selectionapply", FlowEnum.ProcessState.Finished, params);
        List<SelectionApply> proInfoList;
        if (pager.getTotalCount() > 0){
            proInfoList = (List<SelectionApply>) pager.getList();
        }else{
            proInfoList = new ArrayList<>();
        }
        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(SelectionApply mproInfo:proInfoList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",mproInfo.getId());
            rMap.put("name",mproInfo.getName());
            //rMap.put("no",mproInfo.getProjectNo());
            rMap.put("create",mproInfo.getCreater().getName());

            String sAddr = "";

            // rMap.put("buildAddress" , mproInfo.getBuildAddress());

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }


        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String list(){

        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //公告对象
        selectionNotice=new SelectionNotice();
        if(StringUtils.isNotEmpty(parentId)){
            String[] str=parentId.split(",");
            for(int i=0;i<str.length-1;i++){
                if(str[i].trim()==str[i+1].trim()){
                    str[i] = "";
                }
            }
            for(int j=0;j<str.length;j++){
                if(str[j] != ""){
                    selectionNotice=selectionNoticeService.get(str[j].trim());
                }
            }
            params.put("selectionNotice",selectionNotice);
        }

        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);

        viewtype="";
        if(StringUtils.isNotEmpty(viewtype)){
            if(viewtype.equals("1")){
                //流转中
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed});
                pager=selectionApplyService.findByPagerAndLimit(false, "selectionapply", pager, params);
            }else if(viewtype.equals("2")){
                //已归档
                params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished});
                pager=selectionApplyService.findByPagerAndFinish("selectionapply", pager, params);
            }
        }else{
            //所有单子
            params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
            pager=selectionApplyService.findByPagerAndLimit(true, "selectionapply", pager, params);
        }

        List<SelectionApply> selectionApplysList;
        if (pager.getTotalCount() > 0){

            selectionApplysList = (List<SelectionApply>) pager.getList();
        }else{
            selectionApplysList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(SelectionApply selectionApply:selectionApplysList){

            SimpleDateFormat simpleDateFormat= new SimpleDateFormat("yyyy-MM-dd");
            rMap=new HashMap<>();
            rMap.put("id",selectionApply.getId()!=null?selectionApply.getId():"");
            rMap.put("creater",selectionApply.getCreater()!=null?selectionApply.getCreater().getName():"");
            rMap.put("createDate",selectionApply.getCreateDate()!=null?simpleDateFormat.format(selectionApply.getCreateDate()):"");
            if(selectionApply.getProcessState().name()!=null){
                if(selectionApply.getProcessState().name().equals("Finished")){
                    rMap.put("state","报名完成");
                }else if(selectionApply.getProcessState().name().equals("Deny")){
                    rMap.put("state","报名被否决");
                }else if(selectionApply.getProcessState().name().equals("Running")){
                    rMap.put("state","报名中");
                }else {
                    rMap.put("state","null");
                }
            }
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){
        attchmentList=Lists.newArrayList();
        selectionNotice=new SelectionNotice();

        loginUser = usersService.getLoginInfo();

        if(StringUtils.isNotEmpty( keyId)) {
                Company company = usersService.getCompanyByUser();
                selectionApply = selectionApplyService.get(keyId);
                numStatus = workflowService.getNumStatus(keyId, loginUser);

                //公告对象
                if(selectionApply.getSelectionNotice()!=null){
                    selectionNotice=selectionApply.getSelectionNotice();
                }
                //附件
                if(selectionApply.getAttchment().size()>0){
                    attchmentList=selectionApply.getAttchment();

            }

        }else{
        }

        return "read";

    }

    public String input(){
        attchmentFileId="";//变量从后台传输数据到前台，变量都要初始值，如果不赋值，对象的默认值是null值
        selectionNotice=new SelectionNotice();
        loginUser=usersService.getLoginInfo();
        if (StringUtils.isNotEmpty(keyId)){
            selectionApply = selectionApplyService.get(keyId);
            Company company = usersService.getCompanyByUser();
            //附件
            if(selectionApply.getAttchment().size()>0){
                for (FileManage fileManage:selectionApply.getAttchment()){
                    attchmentFileId+=fileManage.getId()+",";
                }
            }
            //公告对象
            selectionNotice=selectionApply.getSelectionNotice();
        } else {
            applyUserName1=loginUser.getName();
        }



        return "input";
    }

    private void setData(){
        attchmentList=Lists.newArrayList();
        selectionNotice=new SelectionNotice();
        if(StringUtils.isNotEmpty(keyId)){
            selectionApply = selectionApplyService.get(keyId);

        }else{
            selectionApply = new SelectionApply();
            selectionApply.setCreater(usersService.getLoginInfo());

        }
        //公告对象
        if(StringUtils.isNotEmpty(parentId)){
            String[] str=parentId.split(",");
            for(int i=0;i<str.length-1;i++){
                if(str[i].trim()==str[i+1].trim()){
                    str[i] = "";
                }
            }
           for(int j=0;j<str.length;j++){
                if(str[j] != ""){
                    selectionNotice=selectionNoticeService.get(str[j].trim());
                }
           }
        }
        //附件判断
        if(StringUtils.isNotEmpty(attchmentId)){
            for (String s:attchmentId.split(",")){
                attchmentList.add(fileManageService.get(s.trim()));

            }
        }
        selectionApply.setAttchmentText(attchmentText);
        selectionApply.setAttchment(attchmentList);
        selectionApply.setRemark(remark);
        selectionApply.setCreateDate(new Date());
        selectionApply.setSelectionNotice(selectionNotice);

        selectionApplyService.save(selectionApply);
        selectionApply.setCompany(usersService.getLoginInfo().getCompany());
    }

    // 保存
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                selectionApplyService.update(selectionApply);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("curDutyId", curDutyId);
                various.put("initDuty", curDutyId);
                selectionApplyService.save(selectionApply, "selectionapply", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    // 提交
    public String commit(){
        setData();
        selectionNotice=new SelectionNotice();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        var2.put("initDuty", curDutyId);

        ArrayList<String> list = new ArrayList<String>();
        if(StringUtils.isNotEmpty(parentId)){
            String[] str=parentId.split(",");
            for(int i=0;i<str.length-1;i++){
                if(str[i].trim()==str[i+1].trim()){
                    str[i] = "";
                }
            }
            for(int j=0;j<str.length;j++){
                if(str[j] != ""){
                    selectionNotice=selectionNoticeService.get(str[j].trim());
                }
            }
        }
        Role role=selectionNotice.getRole();
        for(Users users:role.getUsersSet()){
            list.add(users.getId());
        }
        var2.put("approvers", list);    // 会签人Ids
        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                selectionApplyService.approve(selectionApply, FlowEnum.ProcessState.Running, var2, curDutyId,comment);
            } else {
                selectionApplyService.commit(selectionApply, "selectionapply", var1, var2, curDutyId);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    //审批
    public String approve1(){
        selectionApply = selectionApplyService.get(keyId);
        Map<String, Object> var1 = new HashMap<String, Object>();

        var1.put("numStatus", 2);
        var1.put("curDutyId", curDutyId);

        if(StringUtils.isEmpty(comment)){
            comment="";
        }
        try {
            if (StringUtils.isNotEmpty(keyId)) {
                selectionApplyService.approve(selectionApply, FlowEnum.ProcessState.Running, var1, curDutyId, comment);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }
        catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }
    // 会签
    public String approve2() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        Map<String, Object> var2 = new HashMap<String, Object>();

        selectionApply = selectionApplyService.get(keyId);
        /*Task task=workflowService.getCurrentTask(keyId, usersService.getLoginInfo());
      

        int multComplete = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfCompletedInstances");
        int nrOfInstances = (Integer)runtimeService.getVariable(task.getExecutionId(),"nrOfInstances");
        LogUtil.info("multComplete:"+multComplete);
        LogUtil.info("nrOfInstances:"+nrOfInstances);

        if((double)multComplete/nrOfInstances>=1){
            var2.put("numStatus", 2);
            LogUtil.info("do:numStatus2");
        } else {
            var2.put("numStatus", 1);
            LogUtil.info("do:numStatus1");
        }*/

         var2.put("curDutyId", curDutyId);
        try {

            selectionApplyService.approve(selectionApply, FlowEnum.ProcessState.Running, var2, curDutyId, comment);

            Task overtask = workflowService.getCurrentTask(keyId);
            if(overtask==null){/*没有task就到了归档，所以*/
                SelectionApply selectionApply=selectionApplyService.get(keyId);
                selectionApply.setProcessState(FlowEnum.ProcessState.Finished);
                selectionNotice=selectionApply.getSelectionNotice();
                selectionNotice.setApplyFinished("1");
                selectionNoticeService.update(selectionNotice);
                selectionApplyService.update(selectionApply);


                selectionSpeech= new SelectionSpeech();
                selectionSpeech.setCreater(selectionApply.getCreater());
                selectionSpeech.setCreateDate(new Date());
                selectionSpeech.setSpeechState("竞聘演讲");
                selectionSpeech.setSelectionApply(selectionApply);
                selectionSpeech.setResult("0");
                selectionSpeech.setSelectionNotice(selectionApply.getSelectionNotice());
                selectionSpeech.setCompany(selectionApply.getCreater().getCompany());
                selectionSpeechService.save(selectionSpeech);


                List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(selectionApply.getId());
                for(TaskRecord taskRecord:taskRecords){
                    taskRecord.setType(2);
                    taskRecordService.update(taskRecord);
                }


            }else {
                if(runtimeService.getVariable(overtask.getExecutionId(),"nrOfCompletedInstances")==null){
                    runtimeService.setVariable(overtask.getExecutionId(), "numStatus", 3);
                }
            }
    } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public String approve3() {
        if(StringUtils.isEmpty(keyId))return ajaxHtmlCallback("404", "文档ID未找到！", "操作状态");
        if(StringUtils.isEmpty(comment)) comment="";
        selectionApply = selectionApplyService.get(keyId);

        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 4);
        //  var2.put("curDutyId", curDutyId);
        try {
            selectionApplyService.approve(selectionApply, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }catch (Exception e){
            return ajaxHtmlCallback("404", "操作异常，请联系管理员！", "操作状态");
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    /**
     * 退回
     * @return
     */
    public String reject() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            selectionApply = selectionApplyService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("selectionapply");
            String key=activityList.get(0).getId();
            System.out.println("Activity key:"+key);
            System.out.println("comment:"+comment);
            LogUtil.info("numStatus:"+numStatus);
            if(StringUtils.isEmpty(comment)) comment="";
            selectionApplyService.reject(selectionApply, key, numStatus, comment, curDutyId);
        }

        return ajaxHtmlCallback("200", "退回成功！", "操作状态");
    }

    /**
     * 否决
     * @return
     */
    public String deny() {
        if (com.joint.base.util.StringUtils.isNotEmpty(keyId)) {
            selectionApply = selectionApplyService.get(keyId);
            List<ActivityImpl> activityList= workflowService.findAllActivitiesByKey("selectionapply");
            String key= activityList.get(activityList.size()-1).getId();
            System.out.println("Activity key:"+key);
            if(com.joint.base.util.StringUtils.isEmpty(comment)){
                comment="";
            }
            selectionApplyService.deny(selectionApply, key, comment, curDutyId);
        }
        return ajaxHtmlCallback("200", "否决成功！", "操作状态");
    }



    public SelectionApply getSelectionApply() {
        return selectionApply;
    }

    public void setSelectionApply(SelectionApply selectionApply) {
        this.selectionApply = selectionApply;
    }
    @Override
    public int getNumStatus() {
        return numStatus;
    }

    @Override
    public void setNumStatus(int numStatus) {
        this.numStatus = numStatus;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getViewtype() {
        return viewtype;
    }
    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }







    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }


    public String getApplyUserName1() {
        return applyUserName1;
    }

    public void setApplyUserName1(String applyUserName1) {
        this.applyUserName1 = applyUserName1;
    }

    public String getApplyUserId() {
        return applyUserId;
    }

    public void setApplyUserId(String applyUserId) {
        this.applyUserId = applyUserId;
    }




    public String getApplyUserDate() {
        return applyUserDate;
    }

    public void setApplyUserDate(String applyUserDate) {
        this.applyUserDate = applyUserDate;
    }

    public String getAttchmentId() {
        return attchmentId;
    }

    public void setAttchmentId(String attchmentId) {
        this.attchmentId = attchmentId;
    }

    public String getCheckUsersId() {
        return checkUsersId;
    }

    public void setCheckUsersId(String checkUsersId) {
        this.checkUsersId = checkUsersId;
    }

    public String getAttchmentFileId() {
        return attchmentFileId;
    }

    public void setAttchmentFileId(String attchmentFileId) {
        this.attchmentFileId = attchmentFileId;
    }

    public String getAttchmentText() {
        return attchmentText;
    }

    public void setAttchmentText(String attchmentText) {
        this.attchmentText = attchmentText;
    }

    public List<FileManage> getAttchmentList() {
        return attchmentList;
    }

    public void setAttchmentList(List<FileManage> attchmentList) {
        this.attchmentList = attchmentList;
    }


    public SelectionNotice getSelectionNotice() {
        return selectionNotice;
    }

    public void setSelectionNotice(SelectionNotice selectionNotice) {
        this.selectionNotice = selectionNotice;
    }

    public SelectionSpeech getSelectionSpeech() {
        return selectionSpeech;
    }

    public void setSelectionSpeech(SelectionSpeech selectionSpeech) {
        this.selectionSpeech = selectionSpeech;
    }

    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    @Override
    public String getTodo() {
        return todo;
    }

    @Override
    public void setTodo(String todo) {
        this.todo = todo;
    }
}


